<?php
namespace App\Services;

use App\Model\PositionSupervise;
use App\Model\PositionSuperviseSheet;
use App\Model\SuperviseSheetAssign;
use App\Repositories\CompanyUnitRepository;
use App\Repositories\PositionPaperRepository;
use App\Repositories\PositionSuperviseRepository;
use App\Repositories\PositionSuperviseSheetRepository;
use App\Repositories\SuperviseSheetAssignRepository;
use App\Repositories\SuperviseSheetReplyRepository;
use App\Traits\ReturnTrait;
use Hyperf\DbConnection\Db;

class PositionSuperviseService
{
    use ReturnTrait;

    public function sheetAssign($params,$user,$user_type="admin"){
        $id = $params['id'];
        $sheet = PositionSuperviseSheetRepository::getInstance()->getById($id);
        if(!$sheet){
            return $this->error('数据不存在');
        }
        DB::beginTransaction();
        try{
            $sheet->unit_id = $params['unit_id'];
            $sheet->sheet_status = PositionSuperviseSheet::SHEET_STATUS_ASSIGN;
            if(!$sheet->save()){
                throw new \Exception('分配单位更新失败');
            }
            $assign_record = SuperviseSheetAssignRepository::getInstance()->one('*',[[
                'field' => 'sheet_id',
                'value' => $params['id']
            ],[
                'field' => 'feed_status',
                'value' => SuperviseSheetAssign::FEED_STATUS_DEFAULT
            ]]);
            if($assign_record){
                if(!$assign_record->delete()){
                    throw new \Exception('分配单位更新失败');
                }
            }
            $assign_data=[
                'admin_id' => $user->id,
                'supervise_id' => $sheet->supervise_id,
                'sheet_id' => $params['id'],
                'unit_id' => $params['unit_id'],
                'assign_txt' => $params['assign_txt']
            ];

            $result_assign = SuperviseSheetAssignRepository::getInstance()->store($assign_data);
            if(!$result_assign['success']){
                throw new \Exception('分配失败');
            }
            DB::commit();
        }catch(\Throwable $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success($sheet);
    }

    public function sheetReject($params,$user,$user_type="admin"){
        $id = $params['id'];
        $sheet = PositionSuperviseSheetRepository::getInstance()->getById($id);
        if(!$sheet){
            return $this->error('数据不存在');
        }
        $assign = SuperviseSheetAssignRepository::getInstance()->one('*',[[
            'field'=>'sheet_id',
            'value' => $id
        ],[
            'field'=>'unit_id',
            'value' => $user->unit_id
        ],[
            'field'=>'feed_status',
            'value'=>0
        ]]);
        DB::beginTransaction();
        try{
            $sheet->unit_id=0;
            $sheet->sheet_status = PositionSuperviseSheet::SHEET_STATUS_REJECT;
            if(!$sheet->save()){
                throw new \Exception('数据更新失败');
            }
            $assign->feed_status = -1;
            $assign->feed_txt = $params['feed_txt'];
            if(!$assign->save()){
                throw new \Exception('拒绝失败');
            }
            DB::commit();
        }catch(\Throwable $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success($sheet);
    }

    public function sheetReply($params,$user,$user_type="admin"){
        $id = $params['id'];
        $unit=null;
        if($user_type=='admin'&&$user->unit_id){
            $unit = CompanyUnitRepository::getInstance()->getById($user->unit_id);
        }
        $sheet = PositionSuperviseSheetRepository::getInstance()->getById($id);
        if(!$sheet){
            return $this->error('数据不存在');
        }
        DB::beginTransaction();
        try{
            $reply_insert_data=[];
            $reply_insert_data['id']=0;
            $reply_insert_data['supervise_id'] = $sheet->supervise_id;
            $reply_insert_data['sheet_id'] = $id;
            $reply_insert_data['reply_txt'] = $params['reply_txt'];

            if(isset($params['image'])){
                $image_arr = explode(',',$params['image']);
                foreach($image_arr as &$item){
                    $item=str_replace(env('QINBIU_DOMAIN'),'',$item);
                }
                $reply_insert_data['reply_images'] = implode(',',$image_arr);
            }
            $reply_insert_data['unit_id'] = $user->unit_id;
            $reply_insert_data['unit_name'] = object_get($unit,'name','');
            $reply_insert_data['userable_id'] = $user->id;
            $reply_insert_data['userable_type'] = $user_type;
            $result_reply = SuperviseSheetReplyRepository::getInstance()->store($reply_insert_data);
            if(!$result_reply['success']){
                throw new \Exception('回复保存失败');
            }
            $reply = $result_reply['data'];
            $sheet->sheet_status = PositionSuperviseSheet::SHEET_STATUS_REPLY;
            $sheet->reply_txt = $params['reply_txt'];
            $sheet->reply_images = $reply_insert_data['reply_images'];
            if(!$sheet->save()){
                throw new \Exception('状态更新失败');
            }
            $count = PositionSuperviseSheet::query()->where('supervise_id',$sheet->supervise_id)
                ->where('score',0)
                ->where('sheet_status','!=',PositionSuperviseSheet::SHEET_STATUS_REPLY)
                ->count('id');
            $status = !$count?PositionSupervise::STATUS_DONE:PositionSupervise::STATUS_REPLY;
            PositionSupervise::query()->where('id',$sheet->supervise_id)->update([
                'status' => $status
            ]);

            DB::commit();
        }catch(\Throwable $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success($reply);
    }

    public function sheetScore($params,$user,$user_type="admin"){
        $id = $params['id'];
        $unit=null;
        if($user_type=='admin'&&$user->unit_id){
            $unit = CompanyUnitRepository::getInstance()->getById($user->unit_id);
        }
        $sheet = PositionSuperviseSheetRepository::getInstance()->getById($id);
        $question = PositionPaperRepository::getInstance()->one(['score'],[[
            'field' => 'id',
            'value' => $sheet->paper_id
        ]]);
        if(!$sheet){
            return $this->error('数据不存在');
        }
        if(!$question){
            return $this->error('该问题已删除，暂不能打分');
        }
        if($params['score']>$question->score){
            return $this->error('分值超出该问题上限，上限为'.$question->score.'分');
        }
        DB::beginTransaction();
        try{
            $sheet->score = $params['score'];
            $sheet->sheet_status = PositionSuperviseSheet::SHEET_STATUS_SCORE;
            if(!$sheet->save()){
                throw new \Exception('分数保存失败');
            }
            $sum = PositionSuperviseSheet::query()->where('supervise_id',$sheet->supervise_id)
                ->sum('score');
            $all_count = PositionSuperviseSheet::query()->where('supervise_id',$sheet->supervise_id)
                ->count('id');
            $score_count = PositionSuperviseSheet::query()->where('supervise_id',$sheet->supervise_id)
                ->where('sheet_status',PositionSuperviseSheet::SHEET_STATUS_SCORE)
                ->count('id');
            $update=[
                'final_score' => $sum
            ];
            if($score_count==$all_count){
                $update['status'] = PositionSupervise::STATUS_DONE;
                $update['is_grade'] = 1;
            }
            if(!PositionSupervise::query()->where('id',$sheet->supervise_id)->update($update)){
                throw new \Exception('监督总分保存失败');
            }

            DB::commit();
        }catch(\Throwable $e){
            DB::rollBack();
            return $this->error($e->getMessage());
        }
        return $this->success([]);
    }

    public function grade($params,$user,$user_type="admin"){
        $id = $params['id'];
        $supervise = PositionSuperviseRepository::getInstance()->getById($id);
        $supervise->final_score = $params['score'];
        $supervise->is_grade = 1;
        if($supervise->save()){
            return $this->success([]);
        }
        return $this->error('打分失败，稍后再试');
    }
}